﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sunboxsoft.WinForm;
using DevExpress.XtraEditors;
using System.Text.RegularExpressions;

namespace Sunboxsoft.ASMS.Client.UI.Common.Validations
{
    public abstract class TextEditRegexValidation : IValidation
    {
        private TextEdit _textEdit;
        private string _pattern;
        private string _message;
        private bool _isRequired;//是否可为空,true 可为空,false 不可为空
        public TextEditRegexValidation(TextEdit textEdit, string pattern, string message, bool isRequired)
        {
            _textEdit = textEdit;
            _pattern = pattern;
            _message = message;
            _isRequired = isRequired;
            _textEdit.EditValueChanging += new DevExpress.XtraEditors.Controls.ChangingEventHandler(OnEditValueChanging);
        }

        void OnEditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            string value = Convert.ToString(e.NewValue);
            e.Cancel = !ValueChanging(value);
        }

        /// <summary>
        /// 值变动了
        /// </summary>
        /// <param name="newValue"></param>
        /// <returns>true：变动成功,false:变动不成功</returns>
        public abstract bool ValueChanging(string newValue);

        #region IValidation 成员

        public bool Validate(out string message)
        {
            string value = Convert.ToString(_textEdit.EditValue);
            Regex regex = new Regex(_pattern);
            if (_isRequired)//字段可以为空
            {
                if (!string.IsNullOrEmpty(value))
                {
                    if (regex.IsMatch(value))
                    {
                        message = null;
                        return true;
                    }
                }
                else
                {
                    message = null;
                    return true;
                }
            }
            else
            {
                //不可为空
                if (string.IsNullOrEmpty(value))
                {
                    message = string.Format("请输入{0}！", _message);
                    return false;
                }
                if (regex.IsMatch(value))
                {
                    message = null;
                    return true;
                }
            }
            if (string.IsNullOrEmpty(_message))
            {
                message = "格式不匹配！";
            }
            else
            {
                message = string.Format("{0}格式不匹配！", _message);
            }
            return false;
        }
        #endregion
    }
}
